﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace Miao.UI
{
    public static class WorldUIManager
    {
        #region 预定义UI
        static public GameObject uiLinePrefab;
        const string LinePath = "UI/WorldLine";
        #endregion
        static public Canvas WorldCanvas { get; set; }
        static public Transform WorldUITransform { get; set; }
        public const string WorldUIPrefabPath = "WorldUI/";


        //static public GameObject UILinePrfab;
        //static public CachePool<UILine> UILinePool;
        public static Dictionary<string, CachePool<WorldUI>> WorldUIPool;//这里存pool

        static WorldUIManager()
        {
            WorldUIPool = new Dictionary<string, CachePool<WorldUI>>();
            GameObject uiCanvas = new GameObject("WorldUICanvas", typeof(Canvas));
            WorldCanvas = uiCanvas.GetComponent<Canvas>();
            WorldCanvas.renderMode = RenderMode.WorldSpace;
            WorldCanvas.sortingOrder = 10;
            WorldUITransform = uiCanvas.transform;
            GameObject.DontDestroyOnLoad(uiCanvas);

            #region 预定义UI
            uiLinePrefab = Resources.Load<GameObject>(LinePath);
            #endregion
        }
#if UIEX
        static public UILine BindingUILine(Vector3 pos)
        {
            UILine uiLine = CachePoolManager.GetOne<UILine>(uiLinePrefab, WorldUITransform);
            uiLine.transform.position = pos;
            return uiLine;
        }
#endif

        /// <summary>
        /// 通过Resources.Load来读取世界跟随所需的UI
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="BindTraget"></param>
        /// <returns></returns>
        static public T BindingUI<T>(GameObject BindTraget) where T : WorldUI
        {
            CachePool<WorldUI> pool;
            string key = typeof(T).Name;
            if (!WorldUIPool.TryGetValue(key, out pool))
            {
                string path = WorldUIPrefabPath + key;
                GameObject uiPrefab = Resources.Load<GameObject>(path);
                pool = new CachePool<WorldUI>(uiPrefab, WorldUITransform);
                WorldUIPool.Add(key, pool);
            }
            T target = (T)pool.GetOrCreateOne<T>();
            target.Init(BindTraget);
            return target;
        }


        //static public UILine BindingUILine(Vector3 pos)
        //{
        //    UILine hpLine = UILinePool.GetOrCreateOne<UILine>();
        //    hpLine.transform.position = pos;
        //    return hpLine;
        //}
    }
}

